<template>
  <div class="pane-wrapper" ref="outer">
    <div class="pane pane-left" :style="{ width: leftOffsetPercent , paddingRight: `${this.triggerWidth / 2}px`}">
      <slot name="left"></slot>
    </div>
    <div class="pane-trigger" @mousedown="handlerMousedown" :style="{ left: leftOffsetTrigger, width: `${this.triggerWidth}px` }"></div>
    <div class="pane pane-right" :style="{ left: leftOffsetPercent, paddingLeft: `${this.triggerWidth / 2}px` }">
      <slot name="right"></slot>
    </div>
  </div>
</template>

<script>
export default {
  name: 'WSplitPane',
  props: {
    leftOffset: {
      type: Number,
      default: 0.5
    },
    triggerWidth: {
      type: Number,
      default: 8
    },
    min: {
      type: Number,
      default: 0.1
    },
    max: {
      type: Number,
      default: 0.9
    }
  },
  data () {
    return {
      canMove: false,
      initOffset: 0
    }
  },
  computed: {
    leftOffsetPercent () {
      return `${this.leftOffset * 100}%`
    },
    leftOffsetTrigger () {
      return `calc(${this.leftOffset * 100}% - ${this.triggerWidth / 2}px)`
    }
  },
  methods: {
    changeLeftOffset (value) {
      this.$emit('update:leftOffset', value)
    },
    handlerMousedown (event) {
      document.addEventListener('mousemove', this.handlerMousemove)
      document.addEventListener('mouseup', this.handlerMouseup)
      this.initOffset = event.pageX - event.srcElement.getBoundingClientRect().left
      this.canMove = true
    },
    handlerMouseup () {
      this.canMove = false
    },
    handlerMousemove (event) {
      if (this.canMove) {
        // 容器的rect对象，包含距离页面上下左右的距离
        const outerRect = this.$refs.outer.getBoundingClientRect()
        // 获取鼠标的距离左侧的偏移量
        const offset = event.pageX - this.initOffset + this.triggerWidth / 2 - outerRect.left
        // 偏移的百分比=偏移量/容器的宽度
        let leftOffset = offset / outerRect.width
        if(leftOffset < this.min) leftOffset = this.min
        if(leftOffset > this.max) leftOffset = this.max
        this.changeLeftOffset(leftOffset)
      }
    }
  }
}
</script>

<style lang="less" scoped>
.pane-wrapper {
  height: 100%;
  position: relative;
  .pane {
    top: 0;
    position: absolute;
    height: 100%;
    &-left {
      background: palevioletred
    }
    &-right {
      right: 0;
      bottom: 0;
      background: paleturquoise
    }
    &-trigger {
      height: 100%;
      background: palegoldenrod;
      position: absolute;
      top: 0;
      z-index: 10;
      user-select: none;
      cursor: col-resize;
    }
  }
}
</style>

